﻿using AutoMapper;
using MediatR;
using Yuekao.API.Write.Command;
using Yuekao.Domain.API;
using Yuekao.Domain.BaseReposi;
using Yuekao.Domain.Entitys;

namespace Yuekao.API.Write.CommandHander
{
    public class UpdAuditHandler : IRequestHandler<UpdAuditCommand, APIPagging<bool>>
    {
        private readonly IBaseRepository<Doctor> doctorRepo;
        private readonly IMapper mapper;
        private readonly IBaseRepository<Reject> regectRepo;

        public UpdAuditHandler(IBaseRepository<Doctor> doctorRepo, IMapper mapper, IBaseRepository<Reject> regectRepo)
        {
            this.doctorRepo = doctorRepo;
            this.mapper = mapper;
            this.regectRepo = regectRepo;
        }
        /// <summary>
        /// 医生审批
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<APIPagging<bool>> Handle(UpdAuditCommand request, CancellationToken cancellationToken)
        {
            APIPagging<bool> res = new APIPagging<bool>();

            try
            {
                // 获取医生信息
                var doctor = await doctorRepo.GetValues(x => x.DoctorId == request.DoctorId);
                if (doctor == null)
                {
                    res.Code = APIEnum.Fail;
                    res.Message = "未找到指定的医生";
                    res.Data = false;
                    return res;
                }

                // 创建新的 Reject 实体
                var reject = new Reject
                {
                    DoctorId = request.DoctorId,
                    RejectCase = request.RejectCase,
                    Audit = request.Audit
                };

                // 添加 Reject 记录
                regectRepo.Add(reject);

                // 根据 Audit 值自动修改 Doctor 的 ServiceStatus
                if (request.Audit == 2)
                {
                    // Audit = 2，设置 AuditStatus = 3
                    doctor.AuditStatus = 3;
                }
                else if (request.Audit == 1)
                {
                    // Audit = 1，设置 ServiceStatus = 2
                    doctor.AuditStatus = 2;
                }
                // 如果 Audit 是其他值，保持 ServiceStatus 不变

                // 更新医生信息
                doctorRepo.Update(doctor);

                res.Code = APIEnum.Success;
                res.Message = "医生审批成功";
                res.Data = true;
            }
            catch (Exception ex)
            {
                res.Code = APIEnum.Fail;
                res.Message = $"医生审批失败: {ex.Message}";
                res.Data = false;
            }

            return res;
        }
    }
}
